package com.mvc.framework.utils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

public class BeanUtils {

	public static Object fillClazFromRequest(Class claz, HttpServletRequest req) {
		if (claz!=null) {
			try {
				Field[] fields = claz.getDeclaredFields();
				Object result = claz.newInstance();
				for (Field f : fields) {
					if (req.getParameter(f.getName()) != null) {
						f.setAccessible(true);
						f.set(result, req.getParameter(f.getName()));
						f.setAccessible(false);
					}
				}
				return result;
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				System.err.println("严重：claz 装载失败");
			} catch (InstantiationException e) {
				e.printStackTrace();
				System.err.println("严重：claz 装载失败");
			}
		}
		return null;
	}

	public static boolean isBasicDataType(String dataTypeName) {
		String [] dataTypeArray = {"byte", "short", "int", "float", "double", "long", "boolean", "char"};
		boolean isBasicDataType = false;
		if (dataTypeName!=null && !dataTypeName.trim().isEmpty()) {
			for (String dataType : dataTypeArray) {
				if (dataType.equalsIgnoreCase(dataTypeName)) {
					isBasicDataType = true;
					break;
				}
			}
		}
		return isBasicDataType;
	}

	public static Class basicDataType2Class(String dataTypeName) {
		String [] dataTypeArray = {"byte", "short", "int", "float", "double", "long", "boolean", "char"};
		try {
			Class cla = null;
			if (dataTypeName!=null && !dataTypeName.trim().isEmpty()) {
				for (String dataType : dataTypeArray) {
					if (dataType.equalsIgnoreCase(dataTypeName)) {
						if (dataType.equalsIgnoreCase("int")) {
							cla = int.class;
						} else {
							String classTypeName = dataTypeName.substring(0).toUpperCase() + dataTypeName.substring(1, dataTypeName.length());
							cla = Class.forName("java.lang." + classTypeName);
						}
						break;
					}
				}
			}
			return cla;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.err.println("数据类型不正确，数据类型名称：" + dataTypeName);
		}
		return null;
	}
}
